<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import pageExport from '@/components/page-export/index.vue'
import { ElTree } from 'element-plus'
import xtpzService from '@/api/xtpz'
import { AjglgxQueryResult, JnmlQueryResult, MbpzGetOutputDTO } from '@/api/xtpz-dto'
import { ElTable } from 'element-plus'
import wsjgDialog from '../dialogs/wsjg-dialog.vue'
import gdmb from '../components/gdmb.vue'
import { useMainStore } from '@/store/main'
import TreeUtilDTO from '@/utils/tree'
// 入参
const store = useMainStore()
const loading = ref<boolean>(false)
// 生命周期
onMounted(() => {
  // 获取案件类别
  init()
})

/**
 * 初始化
 */
const init = () => {
  showMb.value = true
  getTableData()
  headerIndex.value = 0
}

const form = ref({
  gjz: '',
})

const tableData = ref<any[]>([])
const flatTableData = ref<any[]>([])
const getTableData = () => {
  const params = {
    ...form.value,
    dwbm: '310000',
  }
  loading.value = true
  xtpzService
    .queryAjglgx(params)
    .then((res) => {
      if (res) {
        flatTableData.value = res.data.map((el) => {
          return {
            ...el,
            id: el.mlbh + '-' + el.fmlbh,
          }
        })
        tableData.value = TreeUtilDTO.getTreeData(flatTableData.value || [], 'mlbh', 'fmlbh')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

// 是否展示模板
const showMb = ref<boolean>(true)
/**
 * 卷内表格多选
 */
const multipleJnTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelectionJn = ref<any[]>([])

/**
 * 树节点过滤
 */
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
  children: 'children',
  label: 'mlmc',
}

/*
 * 获取案件类别
 */
const treeData = ref<AjglgxQueryResult[]>([])
const firtsNode = ref<AjglgxQueryResult | null>()

const getAjlb = async () => {
  // 获取案件类别
  const params = {
    gjz: filterText.value,
    dwbm: '310000',
  }
  loading.value = true
  xtpzService
    .queryAjglgxml(params)
    .then((res) => {
      if (res) {
        treeData.value = TreeUtilDTO.getTreeData(res.data || [], 'mlbh', 'fmlbh')
        // 点击第一项
        if (treeData.value.length) {
          firtsNode.value = null
          getFirstNode(treeData.value)
          if (firtsNode.value) {
            handleCheckNode(firtsNode.value)
          }
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 寻找第一个节点叶子结点
 */
const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) {
    return
  }
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
      return
    }
  }
}

/*
 * 点击树节点
 */
// 当前节点
const currentNode = ref<AjglgxQueryResult>()
const handleCheckNode = (node: AjglgxQueryResult) => {
  if (node.ajglgxbm) {
    currentNode.value = node
    // 获取表格
    getAjTableData()
    nextTick(() => {
      treeRef.value!.setCurrentKey(node.mlbh)
    })
  }
}

const switchChange = (e: string, row: any) => {
  const params = {
    mbpzbm: row.mbpzbm,
    sfqy: e,
  }
  xtpzService
    .enableMbpz(params)
    .then(() => {
      ElMessage.success('操作成功')
      getAjTableData()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 当前模版配置编码
const currrentMbpz = ref<MbpzGetOutputDTO>()
const goWsjpz = (row: MbpzGetOutputDTO) => {
  currrentMbpz.value = row
  // 获取卷内目录
  getJnmlData()
  showMb.value = false
}

/**
 * 获取卷内目录
 */
const jnlmList = ref<JnmlQueryResult[]>([])
const getJnmlData = () => {
  const params = {
    gjz: form.value.gjz,
    mbpzbm: currrentMbpz.value?.mbpzbm || '',
  }
  loading.value = true
  xtpzService
    .queryJnml(params)
    .then((res) => {
      if (res) {
        currentJnIndex.value = null
        jnlmList.value = res.data.map((item) => {
          return {
            ...item,
          }
        })
        // if (multipleSelectionJn.value[0]) {
        //   const jnmlbm = multipleSelectionJn.value[0].jnmlbm
        //   nextTick(() => {
        //     const row = jnlmList.value.find((el) => el.jnmlbm === jnmlbm)
        //     multipleJnTableRef.value?.toggleRowSelection(row, true)
        //   })
        // }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

// 案件模板配置
const tableAjData = ref<any[]>([])
const getAjTableData = () => {
  const params = {
    ajglgxbm: currentNode.value?.ajglgxbm || '',
  }
  loading.value = true
  xtpzService
    .queryMbpz(params)
    .then((res) => {
      if (res) {
        tableAjData.value = res.data || []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSelectionJnChange = (val: any[]) => {
  multipleSelectionJn.value = val
  currentJnIndex.value = jnlmList.value.indexOf(val[0])
}
/**
 * 卷内目录当前选中row
 */
const currentJnIndex = ref<number | null>(null)
const rowJnClick = (row: JnmlQueryResult) => {
  currentJnIndex.value = jnlmList.value.indexOf(row)
}

// 刷新
const gdmbRefresh = () => {
  if (showMb.value) {
    getAjTableData()
  } else {
    getJnmlData()
  }
}

// 查询
const queryTableData = () => {
  getJnmlData()
}

/**
 * 返回
 */
const goBack = () => {
  showMb.value = true
  getAjlb()
}

/**
 * 文书挂接
 */
const wsjgDialogRef = ref<InstanceType<typeof wsjgDialog>>()
const wsgj = (row: JnmlQueryResult) => {
  wsjgDialogRef.value!.openDialog(row)
}

/*
 * tabs 切换
 */
const headerIndex = ref(0)
const headerClickChange = (value: number) => {
  if (headerIndex.value === value) return
  headerIndex.value = value
  form.value.gjz = ''
  showMb.value = true
  if (value === 0) {
    getTableData()
  } else {
    getAjlb()
  }
}

const changeMb = (val: boolean) => {
  showMb.value = val
}

defineExpose({ init })
</script>
<template>
  <div class="container" v-loading="loading">
    <!--模板start-->
    <!--按钮组-->
    <div class="btn-box">
      <div class="gdmbpz-header">
        <button
          class="header-text"
          :class="headerIndex === 0 ? 'header-avtive' : ''"
          @click="headerClickChange(0)"
        >
          归档范围配置
        </button>
        <button
          class="header-text"
          :class="headerIndex === 1 ? 'header-avtive' : ''"
          @click="headerClickChange(1)"
        >
          归档模板配置
        </button>
      </div>
      <!-- <div class="table-title">
          <span>归档模板配置</span>
        </div> -->
      <div class="gjz-header" v-if="headerIndex === 0">
        <el-input
          class="small-input"
          v-model="form.gjz"
          maxlength="100"
          placeholder="案件类别关键字"
          @change="getTableData"
        >
          <template #append>
            <el-button @click="getTableData" type="primary">查询</el-button>
          </template>
        </el-input>
        <button class="btn_operation" @click="getTableData">
          <div class="btn-refresh"></div>
          刷新
        </button>
      </div>
      <div class="gjz-header" v-else>
        <el-input
          v-if="!showMb"
          class="small-input"
          v-model="form.gjz"
          maxlength="100"
          placeholder="案件类别关键字"
          @change="queryTableData"
        >
          <template #append>
            <el-button @click="queryTableData" type="primary">查询</el-button>
          </template>
        </el-input>
        <button class="btn_operation" @click="gdmbRefresh">
          <div class="btn-refresh"></div>
          刷新
        </button>
        <button v-if="!showMb" class="btn_operation" @click="goBack">
          <div class="btn-back"></div>
          返回
        </button>
      </div>
    </div>

    <div v-if="headerIndex === 0">
      <el-table
        border
        ref="multipleTableRef"
        :data="tableData"
        highlight-current-row
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column resizable prop="mlmc" label="案卷类别" />
        <el-table-column resizable prop="ywlbmc" label="业务类别" />
        <el-table-column resizable prop="ajlbmc" label="案件类别" />
      </el-table>
    </div>

    <div class="jnbl-box" v-else>
      <template v-if="showMb">
        <div class="left-box">
          <div class="left-box-title table-title">案件类别</div>
          <div class="tree-box">
            <el-input
              v-model="filterText"
              placeholder="案件类别关键字"
              @change="getAjlb"
              maxlength="100"
            >
              <template #append>
                <el-button class="search-btn" type="primary" @click="getAjlb">查询</el-button>
              </template>
            </el-input>
            <el-tree
              ref="treeRef"
              node-key="mlbh"
              class="filter-tree"
              :data="treeData"
              :props="defaultProps"
              default-expand-all
              highlight-current
              @node-click="handleCheckNode"
            >
              <template #default="{ data }">
                <div class="custom-tree-node">
                  <img
                    v-if="data.sfqy === 'N'"
                    style="margin-right: 5px"
                    src="/src/assets/images/text-icon.png"
                    alt=""
                  />
                  <img
                    v-if="data.sfqy === 'Y'"
                    style="margin-right: 5px"
                    src="/src/assets/images/xswjwyz.png"
                    alt=""
                  />
                  <span class="over-title" :title="data.mlmc">{{ data.mlmc }}</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
        <div class="right-box">
          <el-table border ref="multipleTableRef" :data="tableAjData" highlight-current-row>
            <el-table-column type="selection" width="55" />
            <el-table-column resizable prop="ajlbmc" label="案件类别名称" />
            <el-table-column resizable prop="ajlxmc" label="案卷类别" />
            <el-table-column resizable prop="mbpzmc" label="模板名称" />
            <el-table-column resizable prop="mblxmc" label="正副案卷" />
            <el-table-column resizable prop="bz" label="备注" />
            <el-table-column resizable prop="sfqy" label="是否启用模板">
              <template #default="scope">
                <div v-if="scope.row.sfqy === 'N' || !scope.row.sfqy">否</div>
                <div v-else>是</div>
              </template>
            </el-table-column>
            <el-table-column resizable prop="sfqyjnml" label="是否启用卷内目录">
              <template #default="scope">
                <div v-if="scope.row.sfqyjnml === 'N' || !scope.row.sfqyjnml">否</div>
                <div v-else>是</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="130">
              <template #default="scope">
                <el-link link type="primary" @click="goWsjpz(scope.row)">卷内目录</el-link>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <!-- <page-export v-model="page" @changeSize="changePageSize" @changeNum="changePageNum" /> -->
        </div>
      </template>

      <template v-else>
        <gdmb :currrentMbpz="currrentMbpz" @changeMb="changeMb"></gdmb>

        <!-- <gdmbJn :currrentMbpz="currrentMbpz" @changeMb="changeMb"></gdmbJn> -->
        <!-- <el-table
          ref="multipleTableRef"
          :data="jnlmList"
          highlight-current-row
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="jnmlmc" label="题名" />
          <el-table-column prop="bz" label="备注" />
          <el-table-column label="操作" width="130">
            <template #default="scope">
              <el-link link type="primary" @click="wsgj(scope.row)">文书挂接</el-link>
            </template>
          </el-table-column>
        </el-table> -->
        <!-- 文书挂接 -->
        <!-- <wsjg-dialog ref="wsjgDialogRef" :ajlbbm="currentNode?.ajlbbm" @refresh="getJnmlData" /> -->
      </template>
    </div>
    <!--模板end-->
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .btn-box {
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    .gdmbpz-header {
      .header-text {
        color: #4a76ab;
      }
      .header-text + .header-text {
        margin-left: 10px;
      }
      .header-avtive {
        color: #fff;
        background-color: #3c89d0;
      }
    }

    .gjz-header {
      display: flex;
      align-items: center;
      .btn_operation {
        margin-left: 10px;
        white-space: nowrap;
      }
    }
  }
  .left-box {
    width: 300px;
    // height: calc(100% - 38px);
    height: 100%;
    float: left;
    margin-right: 10px;
    border: 1px solid #dae4f1;
    .left-box-title {
      height: 41px;
      width: 100%;
      background-color: #ecf1fa;
      display: flex;
      align-items: center;
      padding: 0 10px;
      font-weight: bold;
    }
    .tree-box {
      width: 100%;
      height: calc(100% - 41px);
      padding: 10px;
      display: flex;
      flex-direction: column;
      .search-btn {
        background: #409eff;
        color: #fff;
        border-bottom-left-radius: 0;
        border-top-left-radius: 0;
      }
    }
  }
  .right-box {
    width: calc(100% - 310px);
    // height: calc(100% - 38px);
    height: 100%;
    float: right;
    border: 1px solid #dae4f1;
    border-bottom: none;
    display: flex;
    flex-direction: column;
    // padding: 10px;
    .el-table {
      flex: 1;
      flex-shrink: 0;
      overflow: auto;
    }
    :deep(.page-export) {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
  .el-table {
    .el-table--border::after {
      width: 0;
    }
    :deep(.el-table__cell) {
      border-right: 0 !important;
    }
    :deep(.el-table__border-left-patch) {
      display: none;
    }
    :deep(th:not(.el-table-column--selection):not(:last-child)) {
      .cell {
        border-right: 1px solid #d4d1e1;
      }
    }
  }
}
.tree-box .el-tree {
  flex: 1;
  flex-shrink: 0;
  overflow: auto;
}
.jnbl-box {
  width: 100%;
  height: calc(100% - 38px);

  .el-table {
    flex: 1;
    flex-shrink: 0;
    overflow: auto;
  }
  :deep(.page-export) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

:deep(.el-input-group__append) {
  button {
    background: #409eff;
    color: #fff;
    border-bottom-left-radius: 0;
    border-top-left-radius: 0;
    &:hover {
      background: #79bbff !important;
      color: #fff;
    }
  }
}

.small-input {
  width: 300px;
  margin-right: 10px;
}

.table-title {
  height: 28px;
}
</style>
